// ignore_for_file: prefer_const_constructors, prefer_const_literals_to_create_immutables, use_build_context_synchronously
import 'dart:async';
import 'dart:math';

import 'package:decimal/decimal.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:junyeyishu/ui/home/widgets/QGPlayVideo.dart';

import 'package:junyeyishu/widgets/QGWebViewWidget.dart';
import 'package:junyeyishu/widgets/QGWidget.dart';
import 'package:video_player/video_player.dart';
import 'package:junyeyishu/ui/home/widgets/QGLimitWidget.dart';
import 'package:junyeyishu/ui/home/widgets/QGNFTBuyAlert.dart';
import 'package:junyeyishu/ui/home/widgets/QGOpenWalletWidget.dart';
import 'package:junyeyishu/ui/home/widgets/QGTypeSwitchWidget.dart';
import 'package:junyeyishu/ui/sale/widgets/QGLoading.dart';
import 'package:junyeyishu/utils/utils.dart';
import 'package:junyeyishu/widgets/QGButton.dart';
import 'package:junyeyishu/widgets/QGNavigationBar.dart';

import 'widgets/QG3DWidget.dart';

class QGNFTDetailPage extends StatefulWidget {
  String id;
  QGNFTDetailPage({super.key, required this.id});
  @override
  State<QGNFTDetailPage> createState() => QGNFTDetailPageState();
}

class QGNFTDetailPageState extends State<QGNFTDetailPage> {
  VideoPlayerController controller = VideoPlayerController.network("");

  bool isTrade = true; // 寄售
  bool isMystery = false; // 盲盒

  int select = 0;

  Map<String, dynamic>? data;

  Timer? timer;
  String? countdown;

  //是否已开通钱包
  bool isWallet = false;
  final decimal = Decimal.parse;

  bool isPriority = false;

  bool isMove3D = false;

  @override
  void dispose() {
    timer?.cancel();
    controller.dispose();
    super.dispose();
  }

  @override
  void initState() {
    super.initState();

    onRefresh();
  }

  setupCountdown() {
    countdown = getCountdown(data?["publish_time"]);
    if (countdown != null) {
      timer?.cancel();
      timer = Timer.periodic(const Duration(seconds: 1), (timer) {
        countdown = getCountdown(data?["publish_time"]);
        if (countdown == null) {
          timer.cancel();
        }
        if (mounted) {
          setState(() {});
        }
      });
    }
  }

  setupPlayer() {
    var url = data?["video_url"] ?? "";
    if (url.isEmpty) {
      return;
    }

    controller = VideoPlayerController.network(data?["video_url"])
      ..initialize().then((_) {
        controller.setLooping(true);
        eventBus.fire(EventVideoInitialize());
      });
  }

  url() {
    return url_goods_goodsInfo;
  }

  param() {
    return {"pid": widget.id};
  }

  handleData(ret) {
    data ??= {};
    // data?["is_like"] = int.parse("${ret?["is_liked"]}");
  }

  onRefresh() {
    Network.post(url(), data: param()).then((res) {
      if (!res.success) {
        toast(res.msg);
        return;
      }

      updateCurrentTime(res.data["timestamp"]);

      data = res.data;
      handleData(res.data);
      setupCountdown();
      setupPlayer();
      if (mounted) {
        setState(() {});
      }
    });

    if (User.isLogin) {
      Network.get(url_u_getMergedUserInfo).then((res) {
        if (!res.success) {
          toast(res.msg);
          return;
        }

        isWallet = res.data["huifu_wallet"] == 1;

        if (mounted) {
          setState(() {});
        }
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    if (data == null) {
      return QGLoading();
    }

    return Scaffold(
      body: Stack(
        children: [
          EasyRefresh(
            onRefresh: onRefresh,
            child: SingleChildScrollView(
              physics: isMove3D ? NeverScrollableScrollPhysics() : null,
              child: Stack(
                children: [
                  Column(
                    children: [
                      SizedBox(height: kSafeTop + 48.rpx),
                      Padding(padding: EdgeInsets.symmetric(horizontal: 15),child: 
                       buildTopIntro()
                      ,)
                       ,
                       SizedBox(height: 10.rpx),
                      buildDesc(),
                      SizedBox(height: 10.rpx),
                      buildNotice(),
                      SizedBox(height: 54.rpx + max(kSafeBottom, 10) + 10.rpx),
                    ],
                  ),
                ],
              ),
            ),
          ),
          Positioned(top: 0, child: buildTop()),
          Positioned(bottom: 0, child: buildBottom()),
          Row(),
        ],
      ),
    );
  }

  buildTopIntro() {
    return Stack(
      children: [
        buildImage(),
        Column(
          children: [
            SizedBox(height: 365.rpx),
            Row( mainAxisAlignment: MainAxisAlignment.center,
              children: [
              Column(
                children: [
                   Text(
                   "限量",
                    style: TextStyle(
                        color: Color(0xffffffff),
                        fontSize: 13.rpx,
                       ),
                  ),
                   Text(
                   data?["total"] ?? "",
                    style: TextStyle(
                        color: Color(0xffffffff),
                        fontSize: 24.rpx,
                        fontWeight: FontWeight.bold
                       ),
                  ),
                ],
              ),
              SizedBox(width: 30.rpx,),
              Container(
                height: 30.rpx,
                decoration: BoxDecoration(
                  border: Border(
                    left: BorderSide(
                      color: Color(0XFF484848)
                    )
                  )
                ),
              ),
              SizedBox(width: 30.rpx,),

              Column(
                children: [
                   Text(
                   "流通",
                    style: TextStyle(
                        color: Color(0xffffffff),
                        fontSize: 13.rpx,
                       ),
                  ),
                   Text(
                   "${data?["circulation_amount"]}",
                    style: TextStyle(
                        color: Color(0xffffffff),
                        fontSize: 24.rpx,
                        fontWeight: FontWeight.bold
                       ),
                  ),
                ],
              )
            ],),

            // Row(
            //   mainAxisAlignment: MainAxisAlignment.center,
            //   children: [
            //     QGLimitWidget(num: data?["total"] ?? ""),
            //     SizedBox(width: 12.rpx),
            //     data?["mysterybox"] is List
            //         ? Container()
            //         : QGLimitWidget(num: "${data?["circulation_amount"]}", type: 2)
            //   ],
            // ),
            buildIntro(),
          ],
        )
        
      ],
    );
  }

  buildImage() {
    var glb = data?["glb_url"] ?? "";
    if (glb is String && glb.isNotEmpty) {
      return Listener(
        onPointerDown: (event) {
          isMove3D = true;
          if (mounted) setState(() {});
        },
        onPointerUp: (event) {
          isMove3D = false;
          if (mounted) setState(() {});
        },
        child: SizedBox(
          width: kScreenWidth,
          height: kScreenWidth,
          child: QG3DWidget(glb: glb),
        ),
      );
    }

    var video = data?["video_url"] ?? "";

    return Stack(
      alignment: Alignment.center,
      children: [
        ClipRRect(
          borderRadius:BorderRadius.circular(10.rpx),
          child: GestureDetector(
          onTap: video.isEmpty ? showBigImage : onPlayVideo,
          child:
              QGImage(url: data?["thumb_img"], width: 375.rpx, height: 350.rpx),
        )),
        video.isEmpty
            ? Container()
            : IgnorePointer(child: QGImage(asset: "play"))
      ],
    );
  }

  buildIntro() {
    return Stack(
      children: [
        Container(
          margin: EdgeInsets.only(top: 15.rpx),
          padding: EdgeInsets.all(10.rpx),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(10.rpx),
            color: Color(0xff232A32),
          ),
          child: Column(children: [
            buildIntroHeader(),
            SizedBox(height: 10,),
            buildIntroBottom()
         
          ]),
        ),
      ],
    );
  }
 

  buildIntroHeader() {
    return Column(
      children: [
        Row(
          children: [
            Text(
                data?["name"] ?? "",
                style: TextStyle(
                    color: Color(0xffffffff),
                    fontSize: 20.rpx,
                    fontWeight: FontWeight.bold),
              ),
            Expanded(child: SizedBox()),
            Text(
                '￥',
                style: TextStyle(
                    color: Color(0xffffffff),
                    fontSize: 20.rpx,
                    fontWeight: FontWeight.bold),
              ),
            Text(
                '${data?["price"]}',
                style: TextStyle(
                    color: Color(0xffffffff),
                    fontSize: 30.rpx,
                    fontWeight: FontWeight.bold),
              ),
          ],
        ),
        
      ],
    );
  }

  buildIntroBottom() {
    if (data?["mysterybox"] is List) {
      return buildIntroSSR();
    }
    return Column(
      children: [
        // buildIntroAuthor(),
        // buildIntroNo(),
        SizedBox(height: 10.rpx),
        buildIntroChainInfo(),
      ],
    );
  }

  buildIntroSSR() {
  return  Container(
      alignment: Alignment.topLeft,
    child:Wrap(
    alignment: WrapAlignment.start,
    spacing:10,
    runSpacing:10,
    children: [
        for(var itemData in data?["mysterybox"])
        Stack(
          children: [
        Container(
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(10.rpx),
            color: Color(0XFF0C1012)
          ),
        width: 100.rpx,
        child: 
        Column(
          children: [
            ClipRRect(
                borderRadius: BorderRadius.only(topLeft:Radius.circular(10.rpx),topRight:Radius.circular(10.rpx),),
              child: QGImage(
              url: itemData["thumb_img"],
              width: 100.rpx,
             height: 100.rpx)
            )
              ,
                            SizedBox(height: 12.rpx),

             Text(
                              itemData["name"] ?? "",
                              style: TextStyle(
                                  color: Color(0xFFFFFFFF),
                                  fontSize: 14.rpx,
                                  fontWeight: FontWeight.normal),
                            ),
                            SizedBox(height: 5.rpx),

                            Text(
                              '概率：${itemData["probability"]}',
                              style: TextStyle(
                                  color: Color(0xFF989EA4),
                                  fontSize: 12.rpx,
                                  fontWeight: FontWeight.normal),
                            ),
                             Text(
                              '原价：￥${itemData["price"]}',
                              style: TextStyle(
                                  color: Color(0xFF989EA4),
                                  fontSize: 12.rpx,
                                  fontWeight: FontWeight.normal),
                            ),
                            SizedBox(height: 5.rpx),

          ],
        )
        ,
            ),
            Positioned(
              top:5.rpx,
              left: 5.rpx,
              child:  QGImage(url: itemData["goods_level_img"], height: 40.rpx),)
        
        ],
        )

      ]
    )
  )
  
  ;

 
    return Wrap(
      children: [
         ListView.builder(
        padding: EdgeInsets.zero,
        shrinkWrap: true,
        physics: NeverScrollableScrollPhysics(),
        itemCount: data?["mysterybox"].length ?? 0,
        itemBuilder: 
         (context, index) {
          var itemData = data?["mysterybox"]?[index] ?? {};
          return 
             
          
          Container(
            margin: EdgeInsets.only(bottom: index == 4 ? 0 : 10.rpx),
            padding: EdgeInsets.all(10.rpx),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(6.rpx),
              color: Color(0xFFF8F8F6),
            ),
            child:
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Expanded(
                  child: Row(
                    children: [
                      Stack(
                        children: [
                          ClipRRect(
                            borderRadius: BorderRadius.circular(4.rpx),
                            child: QGImage(
                                url: itemData["thumb_img"],
                                width: 54.rpx,
                                height: 54.rpx),
                          ),
                          Positioned(
                            left: 0,
                            right: 0,
                            bottom: 0,
                            child: Container(
                              alignment: Alignment.center,
                              color: Color.fromRGBO(255, 255, 255, 0.6),
                              child: FittedBox(
                                child: Text(
                                  "总量:${itemData["num"]}",
                                  style: TextStyle(
                                      color: Color(0xFF111111),
                                      fontSize: 8.rpx,
                                      fontWeight: FontWeight.normal),
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                      SizedBox(width: 10.rpx),
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              itemData["name"] ?? "",
                              style: TextStyle(
                                  color: Color(0xFF111111),
                                  fontSize: 14.rpx,
                                  fontWeight: FontWeight.normal),
                            ),
                            SizedBox(height: 12.rpx),
                            Text(
                              '概率：${itemData["probability"]}    原价：￥${itemData["price"]}',
                              style: TextStyle(
                                  color: Color(0xFF999999),
                                  fontSize: 12.rpx,
                                  fontWeight: FontWeight.normal),
                            ),
                          ],
                        ),
                      )
                    ],
                  ),
                ),
                SizedBox(width: 10.rpx),
                QGImage(url: itemData["goods_level_img"], height: 44.rpx),
              ],
            ),

         );
        })
      ],
    );
    
    
  }

  buildIntroAuthor() {
    return Column(
      children: [
        buildIntroAuthorItem(
            data?["artist_avatar"], data?["artist_name"], "品牌方"),
        SizedBox(height: 10.rpx),
        buildIntroAuthorItem(
            data?["author_avatar"], data?["author_name"], "创作方"),
      ],
    );
  }

  buildIntroAuthorItem(url, name, tag) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 10.rpx, vertical: 7.rpx),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(6.rpx),
        color: Color(0xFFDEFF80),
      ),
      child: Row(children: [
        ClipRRect(
            borderRadius: BorderRadius.circular(12.rpx),
            child: QGImage(url: url, width: 24.rpx, height: 24.rpx)),
        SizedBox(width: 8.rpx),
        Expanded(
          child: Text(
            name ?? "",
            maxLines: 2,
            style: TextStyle(
                color: Color.fromRGBO(17, 17, 17, 0.8),
                fontSize: 11.rpx,
                fontWeight: FontWeight.normal),
          ),
        ),
        SizedBox(width: 12.rpx),
        Container(
          height: 20.rpx,
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(4.rpx),
              border: Border.all(color: Color(0xFF111111)),
              color: Color(0xFF111111)),
          padding: EdgeInsets.fromLTRB(9.rpx, 0.rpx, 9.rpx, 0.rpx),
          child: Center(
            child: Text(
              tag ?? "",
              style: TextStyle(
                  color: Color(0xffffffff),
                  fontSize: 10.rpx,
                  fontWeight: FontWeight.normal),
            ),
          ),
        )
      ]),
    );
  }

  buildIntroNo() {
    return Container();
  }

  buildIntroChainInfo() {
    return Container(
      padding: EdgeInsets.fromLTRB(10.rpx, 15.rpx, 10.rpx, 16.5.rpx),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(10.rpx),
        color: Color(0xFF0C1012),
      ),
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                '所属系列',
                style: TextStyle(
                    color: Color(0xFFFFFFFF),
                    fontSize: 13.rpx,
                    fontWeight: FontWeight.normal),
              ),
              Text(
                data?["series_name"] ?? "",
                style: TextStyle(
                    color: Color(0xFFFFFFFF),
                    fontSize: 13.rpx,
                    fontWeight: FontWeight.normal),
              ),
            ],
          ),
          buildIntroChainInfoItem(
              title: "合约地址",
              value: data?["contract_address"] ?? "",
              copy: true),
          // buildOwner(),
        ],
      ),
    );
  }

  buildOwner() {
    return Container();
  }

  buildIntroChainInfoItem({title, value, copy = false}) {
    var showValue = value;
    if (value is String && value.length >= 42) {
      showValue =
          "${value.substring(0, 5)} ***** ${value.substring(value.length - 5, value.length)}";
    }

    return GestureDetector(
      onTap: () {
        if (copy) {
          Clipboard.setData(ClipboardData(text: value));
          toast("复制成功");
        }
      },
      child: Container(
        color: Colors.transparent,
        child: Column(
          children: [
            SizedBox(height: 15.rpx),
            Container(height: 0.5.rpx, color: Color(0xFF232A32)),
            SizedBox(height: 15.rpx),
            Row(
              children: [
                Text(
                  title,
                  style: TextStyle(
                     color: Color(0xFF989EA4),
                      fontSize: 12.rpx,
                      fontWeight: FontWeight.normal),
                ),
                SizedBox(width: 10.rpx),
                Expanded(
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      Flexible(
                        child: Text(
                          showValue,
                          style: TextStyle(
                              color: Color(0xFF989EA4),
                              fontSize: 12.rpx,
                              fontWeight: FontWeight.normal),
                        ),
                      ),
                      copy
                          ? Padding(
                              padding: EdgeInsets.only(left: 5),
                              child: QGImage(asset: "home_copy"))
                          : Container(),
                    ],
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Map webViews = {};
  buildDesc() {
    return Container(
      margin: EdgeInsets.only(left: 10.rpx, right: 10.rpx),
      padding: EdgeInsets.only(top: 10.rpx,bottom: 10.rpx),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(10.rpx),
        color: Color(0xff232A32),
      ),
      child: Column(
        children: [
          Row(
            children: [
              SizedBox(width: 15.rpx,),
              Container(
                  width: 4.rpx,
                  height: 13.rpx,
                  color: Color(0XFF44FFFD),
              ),
              SizedBox(width: 5.rpx,),

              Text('藏品故事',style: TextStyle(fontSize: 15,color: Color(0XFFFFFFFF))),
            ],
          ),
          // QGTypeSwitchWidget(
          //     current: select,
          //     items: ["藏品故事"],
          //     fontSize: 14.rpx,
          //     maxFontSize: 14.rpx,
          //     underline: true,
          //     onSwitch: (idx) {
          //       select = idx;
          //       setState(() {});
          //     }),
          data == null
              ? Container()
              : Stack(
                children: [
                  select == 0
                      ? QGWebViewWidget(
                          str: data?["intro"],
                          bgColor: "#232A32",
                          textColor: "#989EA4")
                      : Container(),
                  select == 1
                      ? QGWebViewWidget(
                          str: data?["author_intro"],
                          bgColor: "#ffffff",
                          textColor: "#111111")
                      : Container(),
                  select == 2
                      ? QGWebViewWidget(
                          str: data?["artist_intro"],
                          bgColor: "#ffffff",
                          textColor: "#111111")
                      : Container(),
                ]
                ),
        ],
      ),
    );
  }

  buildNotice() {
    return Container(
        margin: EdgeInsets.only(left: 10.rpx, right: 10.rpx),
        padding: EdgeInsets.only(top: 10.rpx,left: 15.rpx),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(10.rpx),
          color: Color(0xff232A32),
        ),
        child: Column(
          children: [
            Row(
            children: [
              Container(
                  width: 4.rpx,
                  height: 13.rpx,
                  color: Color(0XFF44FFFD),
              ),
              SizedBox(width: 5.rpx,),
              Text('购买须知',style: TextStyle(fontSize: 15,color: Color(0XFFFFFFFF))),
            ],
          ),
            // Text(
            //   '购买须知',
            //   style: TextStyle(
            //       color: Color(0xFF111111),
            //       fontSize: 14.rpx,
            //       fontWeight: FontWeight.normal),
            // ),
            SizedBox(height: 10.rpx),
            Text(
              getPurchaseNotice(),
              style: TextStyle(
                  height: 1.8,
                  color: Color(0xFF989EA4),
                  fontSize: 12.rpx,
                  fontWeight: FontWeight.normal),
            ),
          ],
        ));
  }

  buildTop() {
    return SizedBox(
      width: kScreenWidth,
      child: QGNavigationBar(),
    );
  }

  buildBottom() {
    if (data == null) return Container();

    var title = "去支付";
    var enable = false;

    var publishTime = 0;
    var endTime = 0;
    var priorityStart = 0;
    var priorityEnd = 0;

    try {
      publishTime =
          DateTime.parse(data?["publish_time"]).millisecondsSinceEpoch;
      endTime = DateTime.parse(data?["end_time"]).millisecondsSinceEpoch;

      priorityStart =
          DateTime.parse(data?["priority_start_time"]).millisecondsSinceEpoch;
      priorityEnd =
          DateTime.parse(data?["priority_end_time"]).millisecondsSinceEpoch;
    } catch (e) {}

    dynamic priorityNum = data?["priority_num"] ?? 0;
    if (priorityNum is String) {
      priorityNum = int.parse(priorityNum);
    }

    int now = getCurrentTime();
    if (now >= priorityStart && now < priorityEnd && priorityNum > 0) {
      enable = true;
      isPriority = true;
    } else if (now < publishTime) {
      enable = false;
      title = "即将开售：$countdown";
    } else if (now >= publishTime && now < endTime) {
      enable = true;
    } else if (now > endTime) {
      enable = false;
      title = "已售罄";
    }

    return Container(
      width: kScreenWidth,
      color: Color(0xff232A32),
      padding:
          EdgeInsets.fromLTRB(10.rpx, 10.rpx, 10.rpx, max(kSafeBottom, 10)),
      child: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
        Text(
          '￥',
          style: TextStyle(
              color: Color(0xFFFFFFFF),
              fontSize: 20.rpx,
              fontWeight: FontWeight.bold),
        ),
         Text(
          '${data?["price"]}',
          style: TextStyle(
              color: Color(0xFFFFFFFF),
              fontSize: 30.rpx,
              fontWeight: FontWeight.bold),
        ),
        Expanded(child: SizedBox()),
        Flexible(
          child: Container(
              alignment: Alignment.center,
              height: 44.rpx,
              width: 210.rpx,
              child: QGButton(
                title: title,
                enable: enable,
                onTap: onPay,
              )),
        )
      ]),
    );
  }

  buildBottom4Trade() {
    return Container(
      width: kScreenWidth,
      color: Color(0xffffffff),
      padding:
          EdgeInsets.fromLTRB(10.rpx, 10.rpx, 10.rpx, max(kSafeBottom, 10)),
      child: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
        Text(
          '￥88',
          style: TextStyle(
              color: Color(0xFF111111),
              fontSize: 26.rpx,
              fontWeight: FontWeight.bold),
        ),
        Stack(
          clipBehavior: Clip.none,
          children: [
            Container(
              color: Colors.amber,
              width: 25.rpx,
              height: 25.rpx,
            ),
            Positioned(
              right: -5.rpx,
              top: -5.rpx,
              child: ClipRRect(
                borderRadius: BorderRadius.circular(10.rpx),
                child: Container(
                  alignment: Alignment.center,
                  color: Colors.red,
                  width: 20.rpx,
                  height: 20.rpx,
                  child: Text(
                    '22',
                    style: TextStyle(
                        color: Color(0xffffffff),
                        fontSize: 10.rpx,
                        fontWeight: FontWeight.normal),
                  ),
                ),
              ),
            )
          ],
        ),
        Flexible(
          child: Container(
            height: 44.rpx,
            width: 210.rpx,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(10.rpx),
              gradient: LinearGradient(
                begin: Alignment.centerLeft,
                end: Alignment.centerRight,
                colors: [Color(0xFFFFF25A), Color(0xFFDCFF72)],
              ),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(
                  '加入购物车',
                  style: TextStyle(
                      color: Color(0xFF111111),
                      fontSize: 16.rpx,
                      fontWeight: FontWeight.bold),
                ),
                Flexible(child: SizedBox(width: 20.rpx)),
                Container(
                    width: 0.5.rpx, height: 22.rpx, color: Color(0x77ffffff)),
                Flexible(child: SizedBox(width: 20.rpx)),
                Text(
                  '去支付',
                  style: TextStyle(
                      color: Color(0xFF111111),
                      fontSize: 16.rpx,
                      fontWeight: FontWeight.bold),
                ),
              ],
            ),
          ),
        )
      ]),
    );
  }

  pid() {
    return widget.id;
  }

  onRecord() {
    Navigator.of(context)
        .pushNamed(PageOpenRecord, arguments: data?["pid"] ?? "");
  }

  showBigImage() {
    showDialog(
        useSafeArea: false,
        context: context,
        builder: (context) {
          return GestureDetector(
            onTap: () {
              Navigator.of(context).pop();
            },
            child: Container(
              color: Color.fromRGBO(0, 0, 0, 0.6),
              width: kScreenWidth,
              height: kScreenHeight,
              child: GestureDetector(
                onLongPress: () {
                  saveImage(data?["thumb_img"]);
                },
                child: Center(
                  child: QGImage(
                      url: data?["thumb_img"], width: kScreenWidth - 20.rpx),
                ),
              ),
            ),
          );
        });
  }

  onPlayVideo() {
    controller.play();

    showDialog(
        context: context,
        builder: (ctx) {
          return QGPlayVideo(controller: controller);
        }).then((value) {
      controller.pause();
      controller.seekTo(Duration.zero);
    });
  }

  checkHF() async {
    if (isWallet) return true;

    var res = await Network.post(url_u_getMergedUserInfo, context: context);
    if (!res.success) {
      toast(res.msg);
      return;
    }

    if (res.data["huifu_wallet"] != 1) {
      QGOpenWalletWidget.show(context, () async {
        Navigator.of(context)
            .pushReplacementNamed(PageSelectWallet)
            .then((value) {
          onRefresh();
        });
      });
      return false;
    }
    return true;
  }

  onPay() async {
    if (!User.isLogin) {
      Navigator.of(context).pushNamed(PageLogin);
      return;
    }

    //是否已开通钱包

    if (!await checkHF()) {
      return;
    }

    var limit = int.parse("${data?["num_limit"] ?? "0"}");
    if (isPriority) {
      limit = int.parse("${data?["priority_num"] ?? "0"}");
    }

    if (limit > 1) {
      QGNFTBuyAlert.show(context, data ?? {}, limit, (count) {
        data?["order_price"] =
            (decimal(data?["price"] ?? "") * decimal("$count"))
                .toStringAsFixed(2);
        data?["num"] = count;
        Navigator.of(context)
            .pushReplacementNamed(PageOrderConfirm, arguments: data);
      });
    } else {
       data?["order_price"] = data?["price"];
       Navigator.of(context).pushNamed(PageOrderConfirm, arguments: data);
    }
  }
}
